package com.riant.cert;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.BreakIterator;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */

public class Util {

    private static final char[] QUOTE_ENCODE = "&quot;".toCharArray();
    private static final char[] AMP_ENCODE = "&amp;".toCharArray();
    private static final char[] LT_ENCODE = "&lt;".toCharArray();
    private static final char[] GT_ENCODE = "&gt;".toCharArray();
    private static final String DEFAULT_SPC_CHAR = "[`~ @#$%^&*+|{}':;',<>/?~@#￥%……&*——+|{}【】'\"；：”“。，、？]";
    private static final String DEFAULT_URL_CHAR = "[`~ #$%^*+|{}';',<>~@#￥%&*——+|{}【】'\"；：”“。，、]";
    private static final String DEFAULT_XML_CHAR = "";
    private static final String LOG_SPC_CHAR = "[(){}',~！……（）——+|{}【】'；”“。，、]";

    private static MessageDigest digest = null;

    public Util() {
    }

    /*
     * public static boolean validateUserName(String username) { Pattern p =
     * Pattern.compile("^\\w+$"); Matcher m = p.matcher(username); if (m.find())
     * { return true; } return false; }
     */
    public static String Array2String(String[] values) {
        String result = "";
        if (values == null) {
            return result;
        }
        int len = values.length;
        for (int i = 0; i < len; i++) {
            result += values[i] + ",";
        }
        if (result.endsWith(",")) {
            result = result.substring(result.length() - 1);
        }
        return result;
    }

    public static String Array2String(Object[] values) {
        String result = "";
        if (values == null) {
            return result;
        }
        int len = values.length;
        for (int i = 0; i < len; i++) {
            result += values[i].toString() + ",";
        }
        if (result.endsWith(",")) {
            result = result.substring(result.length() - 1);
        }
        return result;
    }

    @SuppressWarnings("rawtypes")
    public static String Array2String(List values) {
        String result = "";
        if (values == null) {
            return result;
        }
        int len = values.size();
        for (int i = 0; i < len; i++) {
            result += values.get(i).toString() + ",";
        }
        if (result.endsWith(",")) {
            result = result.substring(result.length() - 1);
        }
        return result;
    }

    /*
     * 转换数组为List
     */
    @SuppressWarnings("rawtypes")
    public final static List arrayToList(String[] args) {
        List list = new ArrayList();
        if (args != null) {
            if (args.length > 0) {
                list = Arrays.asList(args);
            }
        }
        return list;
    }

    @SuppressWarnings("restriction")
    public static String base64Encode(String txt) {
        if (txt != null && txt.length() > 0) {
            txt = new sun.misc.BASE64Encoder().encode(txt.getBytes());
        }
        return txt;
    }

    @SuppressWarnings("restriction")
    public static String base64Encode(byte[] txt) {
        String encodeTxt = "";
        if (txt != null && txt.length > 0) {
            encodeTxt = new sun.misc.BASE64Encoder().encode(txt);
        }
        return encodeTxt;
    }

    @SuppressWarnings("restriction")
    public static String base64decode(String txt) {
        if (txt != null && txt.length() > 0) {
            byte[] buf;
            try {
                buf = new sun.misc.BASE64Decoder().decodeBuffer(txt);
                txt = new String(buf);
            } catch (IOException ex) {
            }
        }
        return txt;
    }

    @SuppressWarnings("restriction")
    public static byte[] base64decodebyte(String txt) {
        byte[] buf = null;
        if (txt != null && txt.length() > 0) {
            try {
                buf = new sun.misc.BASE64Decoder().decodeBuffer(txt);
            } catch (IOException ex) {
            }
        }
        return buf;
    }

    /**
     * 
     * 
     * @param Number
     * @param decimal
     * @return
     */
    public static String ParseDecNumner(String Number, int decimal) {
        String value = null;
        int divid = 1;
        if (decimal > 0) {
            for (int i = 0; i < decimal; i++) {
                divid = divid * 10;
            }
            value = String.valueOf(Float.parseFloat(Number) / (divid * 1.0));
            int pos = value.indexOf(".") + 1;
            pos = value.length() - pos;
            if (pos < decimal) {
                for (int i = pos; i < decimal; i++) {
                    value = value + "0";
                }
            } else if (pos > decimal) {
                value = value.substring(0, value.length() - pos + decimal);
            }
        } else {
            value = Number;
        }
        return value;
    }

    /**
     * 金额转换，flag如果是0，元转为分；flag如果是1，分转为元；
     * 
     * @param flag,txnAt
     * @return
     */
    public static String transTxnAt(int flag, String txnAt) {

        if (txnAt == null || txnAt.equals(""))
            return txnAt;

        BigDecimal tmpTxnAt = new BigDecimal(txnAt);
        // long longTxnAt = Long.parseLong(String.valueOf(tmpTxnAt));
        String objTxnAt = null;
        if (flag == 0) {

            tmpTxnAt = tmpTxnAt.multiply(new BigDecimal(100));

            objTxnAt = String.valueOf(tmpTxnAt.longValue());
        } else
            objTxnAt = ParseDecNumner(txnAt, 2);
        return objTxnAt;

    }

    /**
     * Replaces all instances of oldString with newString in line.
     *
     * @param line
     *            the String to search to perform replacements on
     * @param oldString
     *            the String that should be replaced by newString
     * @param newString
     *            the String that will replace all instances of oldString
     *
     * @return a String will all instances of oldString replaced by newString
     */
    public static final String replace(String line, String oldString, String newString) {
        if (line == null) {
            return null;
        }
        int i = 0;
        if ((i = line.indexOf(oldString, i)) >= 0) {
            char[] line2 = line.toCharArray();
            char[] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while ((i = line.indexOf(oldString, i)) > 0) {
                buf.append(line2, j, i - j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            return buf.toString();
        }
        return line;
    }

    /**
     * Replaces all instances of oldString with newString in line with the added
     * feature that matches of newString in oldString ignore case.
     *
     * @param line
     *            the String to search to perform replacements on
     * @param oldString
     *            the String that should be replaced by newString
     * @param newString
     *            the String that will replace all instances of oldString
     *
     * @return a String will all instances of oldString replaced by newString
     */
    public static final String replaceIgnoreCase(String line, String oldString, String newString) {
        if (line == null) {
            return null;
        }
        String lcLine = line.toLowerCase();
        String lcOldString = oldString.toLowerCase();
        int i = 0;
        if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
            char[] line2 = line.toCharArray();
            char[] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while ((i = lcLine.indexOf(lcOldString, i)) > 0) {
                buf.append(line2, j, i - j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            return buf.toString();
        }
        return line;
    }

    /**
     * Replaces all instances of oldString with newString in line with the added
     * feature that matches of newString in oldString ignore case. The count
     * paramater is set to the number of replaces performed.
     *
     * @param line
     *            the String to search to perform replacements on
     * @param oldString
     *            the String that should be replaced by newString
     * @param newString
     *            the String that will replace all instances of oldString
     * @param count
     *            a value that will be updated with the number of replaces
     *            performed.
     *
     * @return a String will all instances of oldString replaced by newString
     */
    public static final String replaceIgnoreCase(String line, String oldString, String newString, int[] count) {
        if (line == null) {
            return null;
        }
        String lcLine = line.toLowerCase();
        String lcOldString = oldString.toLowerCase();
        int i = 0;
        if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
            int counter = 0;
            char[] line2 = line.toCharArray();
            char[] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while ((i = lcLine.indexOf(lcOldString, i)) > 0) {
                counter++;
                buf.append(line2, j, i - j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            count[0] = counter;
            return buf.toString();
        }
        return line;
    }

    /**
     * Replaces all instances of oldString with newString in line. The count
     * Integer is updated with number of replaces.
     *
     * @param line
     *            the String to search to perform replacements on
     * @param oldString
     *            the String that should be replaced by newString
     * @param newString
     *            the String that will replace all instances of oldString
     *
     * @return a String will all instances of oldString replaced by newString
     */
    public static final String replace(String line, String oldString, String newString, int[] count) {
        if (line == null) {
            return null;
        }
        int i = 0;
        if ((i = line.indexOf(oldString, i)) >= 0) {
            int counter = 0;
            counter++;
            char[] line2 = line.toCharArray();
            char[] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while ((i = line.indexOf(oldString, i)) > 0) {
                counter++;
                buf.append(line2, j, i - j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            count[0] = counter;
            return buf.toString();
        }
        return line;
    }

    /**
     * This method takes a string which may contain HTML tags (ie, &lt;b&gt;,
     * &lt;table&gt;, etc) and converts the '&lt'' and '&gt;' characters to
     * their HTML escape sequences.
     *
     * @param in
     *            the text to be converted.
     * @return the input string with the characters '&lt;' and '&gt;' replaced
     *         with their HTML escape sequences.
     */
    public static final String escapeHTMLTags(String in) {
        if (in == null) {
            return null;
        }
        char ch;
        int i = 0;
        int last = 0;
        char[] input = in.toCharArray();
        int len = input.length;
        StringBuffer out = new StringBuffer((int) (len * 1.3));
        for (; i < len; i++) {
            ch = input[i];
            if (ch > '>') {
                continue;
            } else if (ch == '<') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(LT_ENCODE);
            } else if (ch == '>') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(GT_ENCODE);
            }
        }
        if (last == 0) {
            return in;
        }
        if (i > last) {
            out.append(input, last, i - last);
        }
        return out.toString();
    }

    /**
     * Hashes a String using the Md5 algorithm and returns the result as a
     * String of hexadecimal numbers. This method is synchronized to avoid
     * excessive MessageDigest object creation. If calling this method becomes a
     * bottleneck in your code, you may wish to maintain a pool of MessageDigest
     * objects instead of using this method.
     * <p>
     * A hash is a one-way function -- that is, given an input, an output is
     * easily computed. However, given the output, the input is almost
     * impossible to compute. This is useful for passwords since we can store
     * the hash and a hacker will then have a very hard time determining the
     * original password.
     * <p>
     * In Jive, every time a user logs in, we simply take their plain text
     * password, compute the hash, and compare the generated hash to the stored
     * hash. Since it is almost impossible that two passwords will generate the
     * same hash, we know if the user gave us the correct password or not. The
     * only negative to this system is that password recovery is basically
     * impossible. Therefore, a reset password method is used instead.
     *
     * @param data
     *            the String to compute the hash of.
     * @return a hashed version of the passed-in String
     */
    public synchronized static final String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {
                System.err
                        .println("Failed to load the MD5 MessageDigest. " + "We will be unable to function normally.");
                nsae.printStackTrace();
            }
        }
        // Now, compute hash.
        digest.update(data.getBytes());
        return encodeHex(digest.digest());
    }

    /**
     * Turns an array of bytes into a String representing each byte as an
     * unsigned hex number.
     * <p>
     * Method by Santeri Paavolainen, Helsinki Finland 1996<br>
     * (c) Santeri Paavolainen, Helsinki Finland 1996<br>
     * Distributed under LGPL.
     *
     * @param bytes
     *            an array of bytes to convert to a hex-string
     * @return generated hex string
     */
    public static final String encodeHex(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        int i;

        for (i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString().toUpperCase();
    }

    /**
     * Turns a hex encoded string into a byte array. It is specifically meant to
     * "reverse" the toHex(byte[]) method.
     *
     * @param hex
     *            a hex encoded String to transform into a byte array.
     * @return a byte array representing the hex String[
     */
    public static final byte[] decodeHex(String hex) {
        char[] chars = hex.toCharArray();
        byte[] bytes = new byte[chars.length / 2];
        int byteCount = 0;
        for (int i = 0; i < chars.length; i += 2) {
            byte newByte = 0x00;
            newByte |= hexCharToByte(chars[i]);
            newByte <<= 4;
            newByte |= hexCharToByte(chars[i + 1]);
            bytes[byteCount] = newByte;
            byteCount++;
        }
        return bytes;
    }

    /**
     * Returns the the byte value of a hexadecmical char (0-f). It's assumed
     * that the hexidecimal chars are lower case as appropriate.
     *
     * @param ch
     *            a hexedicmal character (0-f)
     * @return the byte value of the character (0x00-0x0F)
     */
    private static final byte hexCharToByte(char ch) {
        switch (ch) {
        case '0':
            return 0x00;
        case '1':
            return 0x01;
        case '2':
            return 0x02;
        case '3':
            return 0x03;
        case '4':
            return 0x04;
        case '5':
            return 0x05;
        case '6':
            return 0x06;
        case '7':
            return 0x07;
        case '8':
            return 0x08;
        case '9':
            return 0x09;
        case 'a':
            return 0x0A;
        case 'b':
            return 0x0B;
        case 'c':
            return 0x0C;
        case 'd':
            return 0x0D;
        case 'e':
            return 0x0E;
        case 'f':
            return 0x0F;
        }
        return 0x00;
    }

    /**
     * Converts a line of text into an array of lower case words using a
     * BreakIterator.wordInstance().
     * <p>
     *
     * This method is under the Jive Open Source Software License and was
     * written by Mark Imbriaco.
     *
     * @param text
     *            a String of text to convert into an array of words
     * @return text broken up into an array of words.
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static final String[] toLowerCaseWordArray(String text) {
        if (text == null || text.length() == 0) {
            return new String[0];
        }

        ArrayList wordList = new ArrayList();
        BreakIterator boundary = BreakIterator.getWordInstance();
        boundary.setText(text);
        int start = 0;

        for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
            String tmp = text.substring(start, end).trim();
            // Remove characters that are not needed.
            tmp = replace(tmp, "+", "");
            tmp = replace(tmp, "/", "");
            tmp = replace(tmp, "\\", "");
            tmp = replace(tmp, "#", "");
            tmp = replace(tmp, "*", "");
            tmp = replace(tmp, ")", "");
            tmp = replace(tmp, "(", "");
            tmp = replace(tmp, "&", "");
            if (tmp.length() > 0) {
                wordList.add(tmp);
            }
        }
        return (String[]) wordList.toArray(new String[wordList.size()]);
    }

    /**
     * Pseudo-random number generator object for use with randomString(). The
     * Random class is not considered to be cryptographically secure, so only
     * use these random Strings for low to medium security applications.
     */
    private static Random randGen = new Random();

    /**
     * Array of numbers and letters of mixed case. Numbers appear in the list
     * twice so that there is a more equal chance that a number will be picked.
     * We can use the array to get a random number or letter by picking a random
     * array index.
     */
    private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
            + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();

    /**
     * Returns a random String of numbers and letters (lower and upper case) of
     * the specified length. The method uses the Random class that is built-in
     * to Java which is suitable for low to medium grade security uses. This
     * means that the output is only pseudo random, i.e., each number is
     * mathematically generated so is not truly random.
     * <p>
     *
     * The specified length must be at least one. If not, the method will return
     * null.
     *
     * @param length
     *            the desired length of the random String to return.
     * @return a random String of numbers and letters of the specified length.
     */
    public static final String randomString(int length) {
        if (length < 1) {
            return null;
        }
        // Create a char buffer to put random letters and numbers in.
        char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
        }
        return new String(randBuffer);
    }

    /**
     * Intelligently chops a String at a word boundary (whitespace) that occurs
     * at the specified index in the argument or before. However, if there is a
     * newline character before <code>length</code>, the String will be chopped
     * there. If no newline or whitespace is found in <code>string</code> up to
     * the index <code>length</code>, the String will chopped at
     * <code>length</code>.
     * <p>
     * For example, chopAtWord("This is a nice String", 10) will return
     * "This is a" which is the first word boundary less than or equal to 10
     * characters into the original String.
     *
     * @param string
     *            the String to chop.
     * @param length
     *            the index in <code>string</code> to start looking for a
     *            whitespace boundary at.
     * @return a substring of <code>string</code> whose length is less than or
     *         equal to <code>length</code>, and that is chopped at whitespace.
     */
    public static final String chopAtWord(String string, int length) {
        if (string == null) {
            return string;
        }

        char[] charArray = string.toCharArray();
        int sLength = string.length();
        if (length < sLength) {
            sLength = length;
        }

        // First check if there is a newline character before length; if so,
        // chop word there.
        for (int i = 0; i < sLength - 1; i++) {
            // Windows
            if (charArray[i] == '\r' && charArray[i + 1] == '\n') {
                return string.substring(0, i + 1);
            }
            // Unix
            else if (charArray[i] == '\n') {
                return string.substring(0, i);
            }
        }
        // Also check boundary case of Unix newline
        if (charArray[sLength - 1] == '\n') {
            return string.substring(0, sLength - 1);
        }

        // Done checking for newline, now see if the total string is less than
        // the specified chop point.
        if (string.length() < length) {
            return string;
        }

        // No newline, so chop at the first whitespace.
        for (int i = length - 1; i > 0; i--) {
            if (charArray[i] == ' ') {
                return string.substring(0, i).trim();
            }
        }

        // Did not find word boundary so return original String chopped at
        // specified length.
        return string.substring(0, length);
    }

    /**
     * Escapes all necessary characters in the String so that it can be used in
     * an XML doc.
     *
     * @param string
     *            the string to escape.
     * @return the string with appropriate characters escaped.
     */
    public static final String escapeForXML(String string) {
        if (string == null) {
            return null;
        }
        char ch;
        int i = 0;
        int last = 0;
        char[] input = string.toCharArray();
        int len = input.length;
        StringBuffer out = new StringBuffer((int) (len * 1.3));
        for (; i < len; i++) {
            ch = input[i];
            if (ch > '>') {
                continue;
            } else if (ch == '<') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(LT_ENCODE);
            } else if (ch == '&') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(AMP_ENCODE);
            } else if (ch == '"') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(QUOTE_ENCODE);
            }
        }
        if (last == 0) {
            return string;
        }
        if (i > last) {
            out.append(input, last, i - last);
        }
        return out.toString();
    }

    public static final String escapeForSpecial(String string) {
        if (string == null) {
            return null;
        }
        char ch;
        int i = 0;
        int last = 0;
        char[] input = string.toCharArray();
        int len = input.length;
        StringBuffer out = new StringBuffer((int) (len * 1.3));
        for (; i < len; i++) {
            ch = input[i];
            if (ch > '>') {
                continue;
            } else if (ch == '<') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(LT_ENCODE);
            } else if (ch == '&') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(AMP_ENCODE);
            } else if (ch == '"') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(QUOTE_ENCODE);
            } else if (ch == '>') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(GT_ENCODE);
            }
        }
        if (last == 0) {
            return string;
        }
        if (i > last) {
            out.append(input, last, i - last);
        }
        return out.toString();
    }

    /**
     * Unescapes the String by converting XML escape sequences back into normal
     * characters.
     *
     * @param string
     *            the string to unescape.
     * @return the string with appropriate characters unescaped.
     */
    public static final String unescapeFromXML(String string) {
        string = replace(string, "&lt;", "<");
        string = replace(string, "&gt;", ">");
        string = replace(string, "&quot;", "\"");
        return replace(string, "&amp;", "&");
    }

    private static final char[] zeroArray = "0000000000000000".toCharArray();

    /**
     * Pads the supplied String with 0's to the specified length and returns the
     * result as a new String. For example, if the initial String is "9999" and
     * the desired length is 8, the result would be "00009999". This type of
     * padding is useful for creating numerical values that need to be stored
     * and sorted as character data. Note: the current implementation of this
     * method allows for a maximum <tt>length</tt> of 16.
     *
     * @param string
     *            the original String to pad.
     * @param length
     *            the desired length of the new padded String.
     * @return a new String padded with the required number of 0's.
     */
    public static final String zeroPadString(String string, int length) {
        if (string == null || string.length() > length) {
            return string;
        }
        StringBuffer buf = new StringBuffer(length);
        buf.append(zeroArray, 0, length - string.length()).append(string);
        return buf.toString();
    }

    /**
     * Formats a Date as a fifteen character long String made up of the Date's
     * padded millisecond value.
     *
     * @return a Date encoded as a String.
     */
    public static final String dateToMillis(Date date) {
        return zeroPadString(Long.toString(date.getTime()), 15);
    }

    /**
     * Formats a Date as a fifteen character long String made up of the Date's
     * padded millisecond value.
     *
     * @return a Date encoded as a String.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static final String collectionToString(Collection c, String spilt) {
        if (c == null) {
            return null;
        }
        if (spilt == null) {
            return null;
        }
        String ret = "";
        List a = new ArrayList(c);
        try {
            for (int i = 0; i < a.size(); i++) {
                String t = (String) a.get(i);
                if (i == a.size() - 1) {
                    ret = ret + t;
                } else {
                    ret = ret + t + spilt;
                }
            }
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String genPassword(int length) {
        if (length < 1) {
            return null;
        }
        String[] strChars = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i",
                "j", "k", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a" };
        // 没有0,o,l和I，以免误解
        StringBuffer strPassword = new StringBuffer();
        int nRand = (int) Math.round(Math.random() * 100);
        for (int i = 0; i < length; i++) {
            nRand = (int) Math.round(Math.random() * 100);
            strPassword.append(strChars[nRand % (strChars.length - 1)]);
            // strPassword += strChars[nRand % (strChars.length - 1)];
        }
        return strPassword.toString();
    }

    public static String genNumPassword(int length) {
        if (length < 1) {
            return null;
        }
        String[] strChars = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

        StringBuffer strPassword = new StringBuffer();
        int nRand = (int) Math.round(Math.random() * 100);
        for (int i = 0; i < length; i++) {
            nRand = (int) Math.round(Math.random() * 100);
            strPassword.append(strChars[nRand % (strChars.length - 1)]);
            // strPassword += strChars[nRand % (strChars.length - 1)];
        }
        return strPassword.toString();
    }

    public static String genEmptyString(int length) {
        if (length < 1) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(" ");
        }
        return sb.toString();
    }

    @SuppressWarnings("finally")
    public static String getHTML(String str) {
        String strret = null;
        URL rTmp = null;
        InputStream ins = null;
        BufferedReader breader = null;
        InputStreamReader isreader = null;
        try {
            rTmp = new URL(str);
            ins = rTmp.openStream();
            isreader = new InputStreamReader(ins);
            breader = new BufferedReader(isreader);
            String info = breader.readLine();
            strret = info;
            info = breader.readLine();
            while (info != null) {
                strret = strret + "\n" + info;
                info = breader.readLine();
            }
        } catch (Exception e) {
            // e.printStackTrace(System.err);
            // return null;
        } finally {
            try {
                if (breader != null) {
                    breader.close();
                }
            } catch (IOException ex) {
            }

            try {
                if (isreader != null) {
                    isreader.close();
                }
            } catch (IOException ex1) {
            }

            try {
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex2) {
            }

            return strret;
        }
    }

    public static String getAsciiString(int digit) {
        byte ret[] = new byte[1];
        ret[0] = (byte) digit;
        return new String(ret);
    }

    public static int getAsciiNum(String s) {
        if (s.length() < 1) {
            return 0;
        }
        byte b = s.getBytes()[0];
        return b;
    }

    public static String getCurrDate() {
        Date date = new Date();
        return Util.formatDate4(date);
    }

    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

    public static String getCurrTime2() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("HHmmss");
        String s = outFormat.format(now);
        return s;
    }

    /**
     * Formats a Date object to return a date using the global locale.
     */
    public static String formatDate(Date date) {
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
        return outFormat.format(date);
    }

    /**
     * Formats a Date object to return a date and time using the global locale.
     */
    public static String formatDateTime(Date date) {
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return outFormat.format(date);
    }

    public static String formatDate2(Date myDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        String strDate = formatter.format(myDate);
        return strDate;
    }

    public static String formatDate3(Date myDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm");
        String strDate = formatter.format(myDate);
        return strDate;
    }

    public static String formatDate4(Date myDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String strDate = formatter.format(myDate);
        return strDate;
    }

    public static String formatDate5(Date myDate) {
        String strDate = getYear(myDate) + "-" + getMonth(myDate) + "-" + getDay(myDate);
        return strDate;
    }

    public static String formatDate6(Date myDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String strDate = formatter.format(myDate);
        return strDate;
    }

    /**
     * 格式化金额
     * 
     * @param str
     *            字符串
     * @param len
     *            长度
     * @return
     */
    public static String formatNumber(Object str, int len) {

        if (str == null || str == "") {
            return "0";
        }
        String number = toString(new BigDecimal((String) str), len);
        return replace(number, ".", "");
    }

    public static Date stringToDate(String str, String format) {

        if (str == null || format == null) {
            return null;
        }
        DateFormat sdf = new SimpleDateFormat(format);

        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    public static long Date2Long(int year, int month, int date) {
        Calendar cld = Calendar.getInstance();
        month = month - 1;
        cld.set(year, month, date);
        return cld.getTime().getTime();
    }

    public static long Time2Long(int year, int month, int date, int hour, int minute, int second) {
        Calendar cld = Calendar.getInstance();
        month = month - 1;
        cld.set(year, month, date, hour, minute, second);
        return cld.getTime().getTime();
    }

    public static int getYear(long t) {
        Calendar cld = Calendar.getInstance();
        if (t > 0) {
            cld.setTime(new Date(t));
        }
        return cld.get(Calendar.YEAR);
    }

    public static int getMonth(long t) {
        Calendar cld = Calendar.getInstance();
        if (t > 0) {
            cld.setTime(new Date(t));
        }
        return cld.get(Calendar.MONTH) + 1;
    }

    public static int getDay(long t) {
        Calendar cld = Calendar.getInstance();
        if (t > 0) {
            cld.setTime(new Date(t));
        }
        return cld.get(Calendar.DAY_OF_MONTH);
    }

    public static int getHour(long t) {
        Calendar cld = Calendar.getInstance();
        if (t > 0) {
            cld.setTime(new Date(t));
        }
        return cld.get(Calendar.HOUR_OF_DAY);
    }

    public static int getMinute(long t) {
        Calendar cld = Calendar.getInstance();
        if (t > 0) {
            cld.setTime(new Date(t));
        }
        return cld.get(Calendar.MINUTE);
    }

    public static int getSecond(long t) {
        Calendar cld = Calendar.getInstance();
        if (t > 0) {
            cld.setTime(new Date(t));
        }
        return cld.get(Calendar.SECOND);
    }

    public static int getYear(Date date) {
        Calendar cld = Calendar.getInstance();
        cld.setTime(date);
        return cld.get(Calendar.YEAR);
    }

    public static int getMonth(Date date) {
        Calendar cld = Calendar.getInstance();
        cld.setTime(date);
        return cld.get(Calendar.MONTH) + 1;
    }

    public static int getDay(Date date) {
        Calendar cld = Calendar.getInstance();
        cld.setTime(date);
        return cld.get(Calendar.DAY_OF_MONTH);
    }

    public static int getHour(Date date) {
        Calendar cld = Calendar.getInstance();
        cld.setTime(date);
        return cld.get(Calendar.HOUR_OF_DAY);
    }

    public static int getMinute(Date date) {
        Calendar cld = Calendar.getInstance();
        cld.setTime(date);
        return cld.get(Calendar.MINUTE);
    }

    public static int getSecond(Date date) {
        Calendar cld = Calendar.getInstance();
        cld.setTime(date);
        return cld.get(Calendar.SECOND);
    }

    public static int getYear() {
        Calendar cld = Calendar.getInstance();
        cld.setTime(new Date());
        return cld.get(Calendar.YEAR);
    }

    public static int getMonth() {
        Calendar cld = Calendar.getInstance();
        cld.setTime(new Date());
        return cld.get(Calendar.MONTH) + 1;
    }

    public static int getDay() {
        Calendar cld = Calendar.getInstance();
        cld.setTime(new Date());
        return cld.get(Calendar.DAY_OF_MONTH);
    }

    /*
     * public static String replaceComma(String text) { if (text != null) { text
     * = text.replaceAll("，", ","); } return text; }
     * 
     * public static String replaceBr(String text) { if (text != null) { text =
     * text.replaceAll("\n", "<BR>"); } return text; }
     */
    public static long getLongTime() {
        return System.currentTimeMillis();
    }

    /**
     * 判断字符串是否为空串（null或者内容为空）
     * 
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if ((null == str) || (str.trim().length() <= 0)) {
            return true;
        }

        return false;
    }

    /**
     * 判断字符串是否为空串（null或者内容为空）
     * 
     * @param str
     * @return
     */
    public static boolean isEmpty(Object str) {
        if ((null == str) || (str == "")) {
            return true;
        }
        return false;
    }

    /**
     * 清除字符串的左右空格
     * 
     * @param str
     * @return:返回清除左右空格后的字符串
     */
    public static String trim(String str) {
        if (null == str || "".equals(str) || str.length() == 0) {
            return "";
        }

        return str.trim();
    }

    @SuppressWarnings("rawtypes")
    public static Map getCurrencyMap() {

        return null;
    }

    public static Calendar getCalendarByString(String str, String format) {
        if (str == null || "".equals(str)) {
            return null;
        }
        // format eg: yyyy-MM-dd HH:mm:ss
        SimpleDateFormat standartDateTimeFormat = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = standartDateTimeFormat.parse(str);

        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c;
    }

    public static Calendar getCalendarByString(String str) {
        if (str == null || "".equals(str)) {
            return null;
        }
        SimpleDateFormat standartDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = standartDateTimeFormat.parse(str);

        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        Calendar c = Calendar.getInstance();

        c.setTime(date);
        return c;
    }

    public static String getDateStringByCalendar(Calendar c) {
        if (c == null)
            return "";
        return c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DATE);
    }

    public static String getDDMMYYToYYMMDD(String strtm) {
        String start_time = "";
        String start_date = "";
        String str_year = "";
        String str_date = "";
        String str_month = "";
        int k = 0;
        StringTokenizer st1 = new StringTokenizer(strtm);

        while (st1.hasMoreTokens()) {
            if (k == 0)
                start_date = (String) st1.nextToken();
            if (k == 1)
                start_time = (String) st1.nextToken();
            k++;
        }
        StringTokenizer st2 = new StringTokenizer(start_date + "-", "-");
        str_date = st2.nextToken();
        str_month = st2.nextToken();
        str_year = st2.nextToken();
        return (str_year + "-" + str_month + "-" + str_date + " " + start_time).trim();
    }

    public static String getFormatYYMMDDHHMMSS(String strtm) {
        String start_time = "";
        String start_date = "";
        String str_year = "";
        String str_date = "";
        String str_month = "";
        String str_hour = "";
        String str_minute = "";
        String str_second = "";

        int k = 0;
        if (strtm.trim().equals(""))
            return strtm.trim();
        StringTokenizer st1 = new StringTokenizer(strtm);

        while (st1.hasMoreTokens()) {
            if (k == 0)
                start_date = (String) st1.nextToken();
            if (k == 1)
                start_time = (String) st1.nextToken();
            k++;
        }

        StringTokenizer st2 = new StringTokenizer(start_date + "-", "-");
        str_year = st2.nextToken();
        str_month = st2.nextToken();
        if (str_month.length() == 1)
            str_month = "0" + str_month;

        str_date = st2.nextToken();
        if (str_date.length() == 1)
            str_date = "0" + str_date;
        if (!start_time.trim().equals("")) {
            st2 = new StringTokenizer(start_time + ":", ":");

            str_hour = st2.nextToken();
            if (str_hour.length() == 1)
                str_hour = "0" + str_hour;
            str_minute = st2.nextToken();
            if (str_minute.length() == 1)
                str_minute = "0" + str_minute;
            str_second = st2.nextToken();
            if (str_second.length() == 1)
                str_second = "0" + str_second;
            start_time = (str_hour + ":" + str_minute + ":" + str_second).substring(0, 8);
        }
        return (str_year + "-" + str_month + "-" + str_date + " " + start_time).trim();
    }

    public static String getFormatYYMMDDHHMM(String strtm) {
        String start_time = "";
        String start_date = "";
        String str_year = "";
        String str_date = "";
        String str_month = "";
        String str_hour = "";
        String str_minute = "";
        String str_second = "";

        int k = 0;
        if (strtm.trim().equals(""))
            return strtm.trim();
        StringTokenizer st1 = new StringTokenizer(strtm);

        while (st1.hasMoreTokens()) {
            if (k == 0)
                start_date = (String) st1.nextToken();
            if (k == 1)
                start_time = (String) st1.nextToken();
            k++;
        }

        StringTokenizer st2 = new StringTokenizer(start_date + "-", "-");
        str_year = st2.nextToken();
        str_month = st2.nextToken();
        if (str_month.length() == 1)
            str_month = "0" + str_month;

        str_date = st2.nextToken();
        if (str_date.length() == 1)
            str_date = "0" + str_date;
        if (!start_time.trim().equals("")) {
            st2 = new StringTokenizer(start_time + ":", ":");

            str_hour = st2.nextToken();
            if (str_hour.length() == 1)
                str_hour = "0" + str_hour;
            str_minute = st2.nextToken();
            if (str_minute.length() == 1)
                str_minute = "0" + str_minute;
            str_second = st2.nextToken();
            if (str_second.length() == 1)
                str_second = "0" + str_second;

            start_time = (str_hour + ":" + str_minute + ":" + str_second).substring(0, 5);

        }
        return (str_year + "-" + str_month + "-" + str_date + " " + start_time).trim();
    }

    public static String chkNull(Object obj) {
        if (obj == null) {
            return "";
        }
        if (((String) obj).equalsIgnoreCase("null")) {
            return "";
        }
        return (String) obj;
    }

    public static String chkNullTrim(Object obj) {
        if (obj == null) {
            return "";
        }
        if (((String) obj).equalsIgnoreCase("null")) {
            return "";
        }
        return Util.replace(((String) obj).trim(), " ", "");
    }

    public static String chkNullSpaceOne(Object obj) {
        if (obj == null) {
            return "　";
        }
        if (((String) obj).equalsIgnoreCase("null")) {
            return "　";
        }
        return ((String) obj).trim();
    }

    public static String chkNullCharacterTrim(Object obj) {
        if (obj == null) {
            return "";
        }
        if ((obj.toString()).equalsIgnoreCase("null")) {
            return "";
        }
        return ((String) obj.toString()).trim();
    }

    public static String chkBigDecimalNull(Object obj) {

        if (obj == null) {
            return "0";
        }

        String bd = ((BigDecimal) obj).toString();

        if (bd.equalsIgnoreCase("null")) {
            return "0";
        }

        return bd;
    }

    public static BigDecimal chkBigDecimalNullBigD(Object obj) {

        if (obj == null) {
            return new BigDecimal("0");
        }

        String bd = ((BigDecimal) obj).toString();

        if (bd.equalsIgnoreCase("null")) {
            return new BigDecimal("0");
        }

        return (BigDecimal) obj;
    }

    public static String chkIntegerNull(Object obj) {

        if (obj == null) {
            return "0";
        }

        String bd = ((Integer) obj).toString();

        if (bd.equalsIgnoreCase("null")) {
            return "0";
        }

        return bd;
    }

    public static Integer chkIntegerNullInt(Object obj) {

        if (obj == null) {
            return new Integer("0");
        }

        String bd = ((Integer) obj).toString();

        if (bd.equalsIgnoreCase("null")) {
            return new Integer("0");
        }

        return (Integer) obj;
    }

    public static Short chkShortNullSht(Object obj) {

        if (obj == null) {
            return new Short("0");
        }

        String bd = ((Short) obj).toString();

        if (bd.equalsIgnoreCase("null")) {
            return new Short("0");
        }

        return (Short) obj;
    }

    @SuppressWarnings("rawtypes")
    public static String getHTMLComboString(HashMap typeList, ArrayList typeKeys, String nowValue) {
        String rtStr = "";
        StringBuffer strBuf = new StringBuffer();
        strBuf.append("<option></option>");

        for (int i = 0; i < typeKeys.size(); i++) {
            String org_no = (String) typeKeys.get(i);
            strBuf.append("<OPTION value='" + org_no + "' ");
            if (org_no.equals(nowValue))
                strBuf.append("selected");
            strBuf.append(" >");
            strBuf.append(typeList.get(org_no));
            strBuf.append(" </OPTION> ");
        }
        rtStr = strBuf.toString();
        return rtStr;
    }

    @SuppressWarnings("rawtypes")
    public static String getHTMLComboString2(HashMap typeList, ArrayList typeKeys, String nowValue) {
        String rtStr = "";
        StringBuffer strBuf = new StringBuffer();

        for (int i = 0; i < typeKeys.size(); i++) {
            String org_no = (String) typeKeys.get(i);
            strBuf.append("<OPTION value='" + org_no + "' ");
            if (org_no.equals(nowValue))
                strBuf.append("selected");
            strBuf.append(" >");
            strBuf.append(typeList.get(org_no));
            strBuf.append(" </OPTION> ");
        }
        rtStr = strBuf.toString();
        return rtStr;
    }

    /**
     * 将字符串按指定的符号分割成数组（数组内容不包括指定符号）
     * 
     * @param value
     * @param split
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static String[] splitString(String value, String split) {
        value = Util.trim(value);
        if (Util.isEmpty(value) || Util.isEmpty(split)) {
            return null;
        }

        Collection coll = new ArrayList();
        int StartIndex = 0;
        int EndIndex = value.indexOf(split, StartIndex);
        while (EndIndex >= 0) {
            coll.add(value.substring(StartIndex, EndIndex));
            StartIndex = EndIndex + split.length();
            EndIndex = value.indexOf(split, StartIndex);
        }
        coll.add(value.substring(StartIndex, value.length())); // 剩余字符
        // 转成字符串数组
        int i = 0;
        String vals[] = new String[coll.size()];
        for (Iterator iter = coll.iterator(); iter.hasNext();) {
            vals[i++] = Util.trim((String) (iter.next()));
        }

        return vals;
    }

    /**
     * 字符串填充函数
     *
     * @param string
     * @param filler
     * @param totalLength
     * @param atEnd
     * @return 字符填充后的string
     */
    public static String fillString(String string, char filler, int totalLength, boolean atEnd) {

        byte[] tempbyte = (string == null ? "" : string).getBytes();

        int currentLength = tempbyte.length;

        int delta = totalLength - currentLength;

        for (int i = 0; i < delta; i++) {

            if (atEnd) {

                string += filler;

            }

            else {

                string = filler + string;

            }

        }

        return string;

    }

    /**
     * 把 数组1 与数组2 相加。
     * 
     * @param src
     *            开始数组，
     * @param dst
     *            结束数组
     * @return 返回 开始数组+结束数据
     */
    public static byte[] appendArray(byte[] src, byte[] dst) {
        byte[] newBytes = new byte[src.length + dst.length];
        System.arraycopy(src, 0, newBytes, 0, src.length);
        System.arraycopy(dst, 0, newBytes, src.length, dst.length);
        return newBytes;
    }

    /**
     * 构造实例方法名
     * 
     * @param str
     *            字符串
     * @return set方法名
     */
    public static String methodName(String str) {
        String prefix = str.substring(0, 1).toUpperCase();
        String postfix = str.substring(1);
        return "set" + prefix + postfix;
    }

    /**
     * 补空字符串
     * 
     * @param str
     *            字符串
     * @param length
     *            长度
     * @return 返回补空字符串
     */
    public static String fillStrToLen(String str, int length) {
        if (str == null)
            str = "";
        int i = 0;
        try {
            i = str.getBytes("GBK").length;
        } catch (UnsupportedEncodingException e) {
        }
        if (length < i) {
            throw new StringIndexOutOfBoundsException(length);
        }
        int j = length - i;
        for (int k = 0; k < j; k++) {
            str = str + " ";
        }
        return str;
    }

    /**
     * 字符串前补0
     * 
     * @param str
     *            字符串
     * @param length
     *            长度
     * @return 返回补0字符串
     */
    public static String fillZeroToLen(String str, int length) {
        if (str == null)
            str = "";
        int i = 0;
        try {
            i = str.getBytes("GBK").length;
        } catch (UnsupportedEncodingException e) {
        }
        if (length < i) {
            throw new StringIndexOutOfBoundsException(length);
        }
        int j = length - i;
        for (int k = 0; k < j; k++) {
            str = "0" + str;
        }
        return str;
    }

    public static String repacleCharacterData(String text) {

        String value = text;

        if (text == null) {
            return "";
        }

        char[] data = text.toCharArray();
        for (int i = 0; i < data.length; i++) {
            char c = data[i];
            int result = c;

            if (result >= 0xD800 && result <= 0xDBFF) {

                int high = c;
                try {
                    int low = text.charAt(i + 1);
                    if (low < 0xDC00 || low > 0xDFFF) {
                        value = String.valueOf(data[i]);
                        text = replace(text, value, "");
                        return text;
                    }
                    result = (high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000;
                    i++;
                } catch (IndexOutOfBoundsException e) {
                    value = String.valueOf(data[i]);
                    text = replace(text, value, "");
                    return text;
                }
            }
            if (!isXMLCharacter(result)) {

                value = String.valueOf(data[i]);
                text = replace(text, value, "");
                return text;
            }
        }

        return text;
    }

    /**
     * 过滤字符串,清除掉所有特殊字符,空格,允许字母、数字、中文
     * 
     * @param obj
     * @return 返回过滤的字符串
     */
    public static String strFilter(Object obj) {

        if (obj == null || obj == "")
            return "";

        String str = (String) obj;
        Pattern p = Pattern.compile(DEFAULT_SPC_CHAR);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 过滤字符串,清除掉所有特殊字符,空格中文
     * 
     * @param obj
     * @return 返回过滤的字符串
     */
    public static String strUrlFilter(Object obj) {

        if (obj == null || obj == "")
            return "";

        String str = (String) obj;
        Pattern p = Pattern.compile(DEFAULT_URL_CHAR);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 过滤字符串 代码扫描添加
     * 
     * @param obj
     * @return 返回过滤的字符串
     */
    public static String xmlStrFilter(Object obj) {

        if (obj == null || obj == "")
            return "";
        String str = (String) obj;
        Pattern p = Pattern.compile(DEFAULT_XML_CHAR);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 过滤字符串,清除掉所有特殊字符,空格,允许字母、数字、中文
     * 
     * @param str
     *            字符串
     * @return 返回过滤的字符串
     */

    public static String strFilterLog(Object obj) {

        if (obj == null || obj == "")
            return "";

        String str = (String) obj;
        Pattern p = Pattern.compile(LOG_SPC_CHAR);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 增加判断ASCII的
     **/
    public static boolean isXMLCharacter(int c) {
        if (c <= 0xD7FF) {
            if (c >= 0x20)
                return true;
            else {
                if (c == '\n')
                    return true;
                if (c == '\r')
                    return true;
                if (c == '\t')
                    return true;
                return false;
            }
        }

        if (c < 0xE000)
            return false;
        if (c <= 0xFFFD)
            return true;
        if (c < 0x10000)
            return false;
        if (c <= 0x10FFFF)
            return true;

        return false;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static String[] split(String s, String sep) {
        try {
            if (s == null)
                return null;
            if (sep == null)
                return new String[] { s };

            ArrayList matchList = new ArrayList();
            int index1 = -1;
            int index2 = -2;

            index2 = s.indexOf(sep);
            while (index2 >= 0) {
                String match = s.substring(index1 + 1, index2);
                matchList.add(match);

                index1 = index2;
                index2 = s.indexOf(sep, index1 + 1);
            }

            if (index1 >= -1 && index2 == -1) {
                String match = s.substring(index1 + 1);
                matchList.add(match);
            }

            if (index2 == -2)
                return new String[] { s };

            int resultSize = matchList.size();
            String[] result = new String[resultSize];
            return (String[]) matchList.subList(0, resultSize).toArray(result);
        } catch (Exception e) {
            return null;
        }
    }

    /* 2016-04-20 chaolumen 2016-04-20 新增方法 add begin */
    // public static Object[] create2DStrArray(Object obj1, Object obj2){
    // Object[] array = new Object[]{obj1,obj2};
    // return array;
    // }

    public static List<String> create2DStrList(String str1, String str2) {
        List<String> list = new ArrayList<String>();
        list.add(str1);
        list.add(str2);
        return list;
    }

    /* 2016-04-20 chaolumen 2016-04-20 新增方法 add end */
    /* 2016-05-11 chaolumen 根据给定的属性，给xml格式的字符串屏蔽指定字符串 add begin */
    @SuppressWarnings("unused")
    public static String ShieldXmlStr(String xmlStr, String propertyStr) {
        Pattern p = Pattern.compile("(" + propertyStr + ")=\"([^\"]+?)\"");
        Matcher matcher = p.matcher(xmlStr);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String group1 = matcher.group(1);
            String group2 = matcher.group(2);
            // System.out.println("group1:"+group1);
            // System.out.println("group2:"+group2);
            String newStr = group1 + "=" + "\"******\"";
            matcher.appendReplacement(sb, newStr);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static String ShieldXmlStrBatch(String xmlStr, List<String> propertyList) {
        System.out.println("enter ShieldXmlStrBatch ....");
        if (propertyList == null) {
            return xmlStr;
        }
        if (propertyList.size() == 0) {
            return xmlStr;
        }
        String resultXml = "";
        String tempStr = xmlStr;
        for (String propertyStr : propertyList) {
            tempStr = ShieldXmlStr(tempStr, propertyStr);
        }
        resultXml = tempStr;
        return resultXml;
    }
    /* 2016-05-11 chaolumen 根据给定的属性，给xml格式的字符串屏蔽指定字符串 add begin */

    /**
     * 判断ip 地址是否为有效IP地址
     * */
    public static boolean isIP(String strIP) {
        if (StringUtils.isEmpty(strIP))
            return false;
        else
            strIP = strIP.trim();
        // String reg =
        // "^(([0-1]?\\d{1,2}|2[0-5][0-5])\\.){3}([0-1]?\\d{1,2}|2[0-5][0-5])$";//错误
        String reg = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
        Pattern p = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(strIP);
        return m.matches();
    }

    /**
     * 判断是否为简单类型，后期有需要，请添加
     * 
     * @param obj
     * @return
     */
    public static boolean isSampleType(Object obj) {
        boolean result = true;
        if (obj == null || obj instanceof String || obj instanceof Long || obj instanceof Integer || obj instanceof Date
                || obj instanceof Float || obj instanceof Double || obj instanceof Enum || obj instanceof BigDecimal || obj instanceof List) {
            return result;
        }
        result = false;
        return result;
    }
    
    /**
     * 对数字进行格式化输出
     * @param bd
     * @param scale:小数点后的位数
     * @return:格式化后的数字
     */
    public static String toString(BigDecimal bd, int scale) {
        if (null == bd) {
            bd = new BigDecimal(0);
        }
        bd = bd.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
        return bd.toString();
    }
}
